from constants import GAN,ZHI
from core.engine.lazy_load import expandItem

__all__ = ['AttrDict','AttrFuncDict','CircleTuple','GanZhiAttrDict']
class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)

    def __getattr__(self, item):
        return self.get(item, None)

    def __setattr__(self, key, value):
        self[key] = value

'''默认内置了 expandItem，除此外 AttrFuncDict 没有其他用途'''
class AttrFuncDict(dict):
    def __init__(self, func=None, *args, **kwargs):
        super(AttrFuncDict, self).__init__(*args, **kwargs)
        self.func = func if func else expandItem

    def __getattr__(self, item):
        # return self.get(item, None)
        return self[item]

    def __setattr__(self, key, value):
        if key in ['func']:
            super(AttrFuncDict, self).__setattr__(key, value)
        else:
            self[key] = value

    def __getitem__(self, item):
        try:
            return super(AttrFuncDict, self).__getitem__(item)
        except KeyError:
            # 使用当前字典作为上下文传递给 func
            value = self.func(item, self)
            self.__setitem__(item, value)
            return value


class GanZhiAttrDict(AttrDict):

    def toName(self, item):
        """
        根据规则转换字典中的值为对应的名称。
        :param item: 键名
        :return: 转换后的值或原始值
        """
        value = self.get(item)
        if isinstance(value, int):
            if item.endswith('g') and len(item) == 2:
                # 对于以'g'结尾且长度为2的项，使用GAN进行转换
                return GAN[value % 10]
            elif len(item) == 1:
                # 对于长度为1的项，使用ZHI进行转换
                return ZHI[value % 12]
        return value

    def toTen(self):
        """
        将所有以'g'结尾且长度为2的字段值为0的项改为10。
        """
        for key in list(self.keys()):
            if key.endswith('g') and len(key) == 2 and self.get(key) == 0:
                self[key] = 10


class CircleTuple(tuple):
    def __getitem__(self, item):
        if item is None:
            return None

        elif item >= len(self):
            item = item % len(self)

        return super().__getitem__(item)

if __name__ == '__main__':
    print('★ expand item ★')
    dct =AttrFuncDict()
    dct.coinNumLst = [1,2,3,2,2,3]
    print(dct['outer'])
    print(dct['inner'])
    print(dct)